package com.youkeda.app.api;

import com.youkeda.app.model.PreSingleRedEnvelope;
import com.youkeda.app.model.RedEnvelope;
import com.youkeda.app.model.Result;
import com.youkeda.app.params.BatchAddPreSingleRedEnvelopeParam;
import com.youkeda.app.service.PreSingleRedEnvelopeService;
import com.youkeda.app.service.RedEnvelopeService;
import com.youkeda.app.util.RandomRedPacket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @ClassName RedEnvelopeApi
 * @Author 刘正星
 * @Date 2020/9/4 8:26
 **/
@RestController
public class RedEnvelopeApi {

    @Autowired
    private RedEnvelopeService redEnvelopeService;
    @Autowired
    private PreSingleRedEnvelopeService preSingleRedEnvelopeService;
    @PostMapping("/createRed")
    public Result<RedEnvelope> create(@RequestBody RedEnvelope redEnvelope){
        Result result = new Result();
        result.setSuccess(false);
        List<PreSingleRedEnvelope> preSingleRedEnvelopes = RandomRedPacket.random(redEnvelope);
        if (redEnvelopeService.save(redEnvelope)==null){
            result.setSuccess(false);
            result.setMessage("插入失败");
            return result;
        }
        preSingleRedEnvelopeService.batchAdd(new BatchAddPreSingleRedEnvelopeParam(preSingleRedEnvelopes));
        if (preSingleRedEnvelopes ==null || CollectionUtils.isEmpty(preSingleRedEnvelopes)){
            result.setMessage("子红包为空");
            result.setSuccess(false);
            return  result;
        }
        result.setSuccess(true);
        result.setMessage("success");
        return result;
    }
}
